package com.xiaoc.bulldozer.controller;

import com.xiaoc.bulldozer.common.ResponseCode;
import com.xiaoc.bulldozer.common.dto.LoginUserDto;
import com.xiaoc.bulldozer.common.dto.MenuNode;
import com.xiaoc.bulldozer.common.model.Action;
import com.xiaoc.bulldozer.facade.PriviledgeFacade;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class CommonController extends AdminBaseController {

    @Resource(name = "priviledgeFacade")
    private PriviledgeFacade priviledgeFacade;

    /**
     * 获取默认菜单url
     * 
     * @param menuNodeList
     * @return
     */
    private static String getDefaultMenuUrl(List<MenuNode> menuNodeList) {
        for (MenuNode menuNode : menuNodeList) {
            if (menuNode.getCurNode().isLeaf()) {
                return menuNode.getCurNode().getUrl();
            }

            if (!CollectionUtils.isEmpty(menuNode.getSubNodeList())) {
                return menuNode.getSubNodeList().get(0).getUrl();
            }
        }
        return "";
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {

        LoginUserDto loginUserDto = getCurrentLoginUser(request, response);

        // 默认跳转到权重最高的菜单页
        List<MenuNode> menuNodeList = priviledgeFacade.getMenuTree(loginUserDto, Action.ADMIN_SYSTEM);
        String defaultMenuUrl = getDefaultMenuUrl(menuNodeList);
        if (!StringUtils.isBlank(defaultMenuUrl)) {
            return redirect(getRequest().getContextPath() + defaultMenuUrl);
        }

        forward(request, response, getRequest().getContextPath() + "/common/exception?msg='没有权限访问'");
        return null;
    }

    @RequestMapping(value = "/common/exception")
    public ModelAndView exception(Integer code, String msg) {

        if (code == null) {
            code = ResponseCode.EXCEPTION.getCode();
        }

        if (msg == null) {
            msg = ResponseCode.EXCEPTION.getMsg();
        }

        return jsonFailed(code, msg);
    }

}
